package com.ssyc.gsk_teacher.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.Constants;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.bean.ResultInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.PickChooseManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyGridView;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.gsk_teacher.R;
import com.ssyc.gsk_teacher.adapter.ShowPicGvAdapter;
import com.ssyc.gsk_teacher.bean.ScoreDetailsInfo;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.iwf.photopicker.PhotoPicker;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnMultiCompressListener;
import okhttp3.Call;

/**
 * 上传学生成绩
 * Created by Administrator on 2018/6/28 0028.
 */

public class TeacherAddStudentScoreActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private ImageView ivBack;
    //姓名
    private TextView tvTitle;
    /**
     * 本次测试分数
     */
    private EditText etScore;
    /**
     * 请输入评语
     */
    private EditText etContent;
    /**
     * 0/200
     */
    private TextView tvShownum;
    private MyGridView mgv;
    private Button btCommit;

    //图片适配器
    private ShowPicGvAdapter adapter;

    //填充适配器的图片地址
    private List<String> mPicPaths;

    //对应的学生对象
    private ScoreDetailsInfo.DataBean info;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.teacher_activity_add_student_score;
    }

    @Override
    protected void init() {
        showContent();

        //初始化视图
        initView();

        //获取传递的值
        initIntent();

        //设置监听
        initListener();

        //设置展示图片的适配器
        initGv();
    }

    /**
     * 获取传递的值
     */
    private void initIntent() {
        info = (ScoreDetailsInfo.DataBean) getIntent().getSerializableExtra("student");
        if (null != info) {
            tvTitle.setText(info.getNAME());
        }
    }

    /**
     * 初始化视图
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tvTitle = findViewById(R.id.tv_st_title);
        etScore = findViewById(R.id.et_this_score);
        etContent = findViewById(R.id.et_input);
        tvShownum = findViewById(R.id.tv_shownum);
        mgv = findViewById(R.id.mgv);
        btCommit = findViewById(R.id.bt_commit);
        btCommit.setOnClickListener(this);
    }


    /**
     * 设置监听的方法
     */
    private void initListener() {
        //输入框的改变监听
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String inputText = etContent.getText().toString().trim();
                if (TextUtils.isEmpty(inputText)) {
                    tvShownum.setText("0/200");
                } else {
                    tvShownum.setText(inputText.length() + "/200");
                }
            }
        });
    }


    /**
     * 设置展示选择图片GridView
     */
    private void initGv() {
        mPicPaths = new ArrayList<>();
        adapter = new ShowPicGvAdapter(this, mPicPaths);
        mgv.setAdapter(adapter);
        mgv.setOnItemClickListener(this);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
        Object itemAdapter = parent.getAdapter();
        if (itemAdapter instanceof ShowPicGvAdapter) {
            if (mPicPaths.size() != 9) {
                if (position == ((ShowPicGvAdapter) itemAdapter).getCount() - 1) {
                    PickChooseManager.startPhotoPickActivity(TeacherAddStudentScoreActivity.this, 9 - mPicPaths.size());
                } else {
                    PickChooseManager.startShowBigActivity(TeacherAddStudentScoreActivity.this, mPicPaths, position);
                }
            } else {
                PickChooseManager.startShowBigActivity(TeacherAddStudentScoreActivity.this, mPicPaths, position);
            }
        }
    }


    /**
     * 请求图库后的回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);

                for (int i = 0; i < photos.size(); i++) {
                    mPicPaths.add(photos.get(i));
                }

                //通知适配器刷新
                adapter.notifyDataSetChanged();
            }
        }
    }


    /**
     * 先判断添加的内容的完整性
     * 然后做图片上传的操作
     */
    private void doUploading() {

        String score = etScore.getText().toString().trim();

        String uploadText = etContent.getText().toString().trim();

        if (TextUtils.isEmpty(score)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请输入分数", 0).show();
            return;
        }
        if (Integer.parseInt(score)>150||Integer.parseInt(score)<0) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请输入0-150范围内的分数", 0).show();
            return;
        }

        if (TextUtils.isEmpty(uploadText)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请输入评语", 0).show();
            return;
        }

        if (mPicPaths == null || mPicPaths.size() == 0) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请上传试卷", 0).show();
            return;
        } else {
            CustomDialogManager.show(this, "上传中...");
            //做压缩处理
            List<File> files = new ArrayList<>();
            for (int i = 0; i < mPicPaths.size(); i++) {
                File file = new File(mPicPaths.get(i));
                files.add(file);
            }

            //使用Luban做压缩图片处理
            Luban.compress(this, files).setMaxSize(150).setMaxHeight(1280).setMaxWidth(720).putGear(Luban.CUSTOM_GEAR).launch(new OnMultiCompressListener() {

                @Override
                public void onStart() {
                    //压缩开始
                }

                @Override
                public void onSuccess(List<File> compreFiles) {
                    //压缩成功后的回调,上传该集合的文件
                    doPostScoreAction(compreFiles, score, uploadText);
                }

                @Override
                public void onError(Throwable e) {
                    //压缩错误
                }
            });
        }
    }


    /**
     * 做上传处理
     *
     * @param compreFiles
     * @param score
     * @param uploadText
     */
    private void doPostScoreAction(List<File> compreFiles, String score, String uploadText) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "40");
        map.put("acc", AccountUtils.getAccount(TeacherAddStudentScoreActivity.this));
        map.put("role", AccountUtils.getRole(TeacherAddStudentScoreActivity.this));
        map.put("rowId", info.getROW_ID() + "");
        map.put("score", score);
        map.put("content", uploadText);

        Map<String, File> fileMap = new HashMap<>();
        if (compreFiles != null && compreFiles.size() != 0) {
            for (int i = 0; i < compreFiles.size(); i++) {
                fileMap.put(System.currentTimeMillis() + i + i + ".jpg", compreFiles.get(i));
            }
        }
        OkHttpUtils.post().url(HttpAdress.UPLOADSCORE).params(map).files("picture", fileMap).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast("服务器异常,上传失败", false);
                CustomDialogManager.dissmiss();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i("test", "返回值是:" + response);
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo res = null;
                    try {
                        res = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }
                    if (null != res) {
                        if ("200".equals(res.getState())) {
                            //返回成功
                            UiUtils.Toast("上传成功", false);
                            //上传成功后通知分数详情界面进行重新请求接口刷新页面数据
                            BusInfo busInfo = new BusInfo();
                            busInfo.setType(TeacherScoreDetailsActivity.UPDATASCORE);
                            busInfo.setAddScore(score);
                            busInfo.setRowId(info.getROW_ID());
                            EventBus.getDefault().post(busInfo);
                            finish();

                        } else {
                            UiUtils.Toast("批准失败,返回异常码是:" + res.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + res.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.bt_commit) {
            //提交
            doUploading();
        }
    }
}
